<?php

namespace util;

use think\facade\Db;

class Curd
{
    /**
     * 解析生成列表页
     * @param $info
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function autoShowData($info)
    {
        $limit = input('param.limit');
        $param = input('param.');

        $table = config('database.connections.mysql.prefix') . $info['table'];

        list($tableDict, $relationDict, $showMap, $field, $searchMap, $where) = self::parseIndexTpl($info, $param);
        $field = rtrim($field, ',');

        return Db::table($table)->field($field)->where($where)->order('id', 'desc')->paginate($limit)
            ->each(function ($item, $key) use ($relationDict) {
                foreach ($item as $k => $v) {
                    if (isset($relationDict[$k])) {
                        $item[$k] = $relationDict[$k][$v]['text'];
                    }
                }
                return $item;
        });
    }

    /**
     * 解析列表页参数
     * @param $info
     * @param array $param
     * @return array
     */
    public static function parseIndexTpl($info, $param = [])
    {
        $conf = json_decode($info['conf_json'], true);
        $tableJson = json_decode($info['form_json'], true);

        $tableDict = [
            'id' => 'ID',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'delete_time' => '删除时间'
        ];
        $relationDict = [];

        foreach ($tableJson as $vo) {
            if (isset($vo['datasourceType'])) {

                if ($vo['datasourceType'] == 'local') {
                    $options = [];
                    foreach ($vo['options'] as $v) {
                        $options[$v['value']] = $v;
                    }
                    $relationDict[$vo['field']] = $options;
                } else {
                    $res = Db::query($vo['remoteOptionValue']);
                    $options = [];
                    foreach ($res as $k => $v) {
                        if ($k == 0) {
                            $checked = true;
                        } else {
                            $checked = false;
                        }

                        $options[$v['value']] = [
                            'text' => $v['text'],
                            'value' => $v['value'],
                            'checked' => $checked
                        ];
                    }

                    $relationDict[$vo['field']] = $options;
                }
            }
            $tableDict[$vo['field']] = $vo['label'];
        }

        $showMap = [];
        $field = '';
        foreach ($conf['list'] as $key => $vo) {
            $field .= $conf['name'][$key] . ',';
            $showMap[] = [
                'title' => $tableDict[$conf['name'][$key]],
                'field' => $conf['name'][$key],
                'unresize' => true,
                'align' => 'center'
            ];
        }

        $showMap[] = [
            'title' => '操作',
            'toolbar' => '#options',
            'unresize' => true,
            'align' => 'center',
            'width' => 180
        ];

        $where = [];
        $searchMap = [];
        foreach ($conf['search'] as $key => $vo) {
            // TODO 仅仅简单的处理成input输入值去搜索
            $searchMap[] = [
                'title' => $tableDict[$conf['name'][$key]],
                'field' => $conf['name'][$key]
            ];

            if (isset($param[$conf['name'][$key]]) && !empty($param[$conf['name'][$key]])) {
                // TODO 目前只做100%匹配
                $where[] = [$conf['name'][$key], '=', $param[$conf['name'][$key]]];
            }
        }

        return [
            $tableDict,
            $relationDict,
            $showMap,
            $field,
            $searchMap,
            $where
        ];
    }

    /**
     * 生成校验规则
     * @param $json
     * @return array
     */
    public static function makeSimpleCheckRule($json)
    {
        $rule = [];
        foreach ($json as $key => $vo) {
            if (isset($vo['required']) && $vo['required'] == 'true') {
                $k = $vo['field'] . '|' . $vo['label'];
                $ruleStr = 'require';
                if ($vo['fieldType'] == 'int') {
                    $ruleStr = 'require|number';
                } else if ($vo['fieldType'] == 'varchar') {
                    $ruleStr = 'require|max:' . $vo['fieldLen'];
                }

                $rule[$k] = $ruleStr;
            }
        }

        return $rule;
    }
}